<template>
  <view class="trust-dashboard">
    <!-- 仪表盘头部 -->
    <view class="dashboard-header">
      <text class="dashboard-title">信任档案仪表盘</text>
      <text class="dashboard-subtitle">分析你的信任关系数据</text>
    </view>

    <!-- 信任概览 -->
    <view class="trust-overview">
      <view class="overview-cards">
        <view class="overview-card">
          <text class="card-value">{{ trustStats.totalCards }}</text>
          <text class="card-label">总卡牌数</text>
        </view>
        <view class="overview-card">
          <text class="card-value">{{ trustStats.averageTrust }}</text>
          <text class="card-label">平均信任</text>
        </view>
        <view class="overview-card">
          <text class="card-value">{{ trustStats.highTrustCards }}</text>
          <text class="card-label">高度信任</text>
        </view>
        <view class="overview-card">
          <text class="card-value">{{ trustStats.brokenTrustCards }}</text>
          <text class="card-label">破裂信任</text>
        </view>
      </view>
    </view>

    <!-- 信任分布图表 -->
    <view class="chart-section">
      <view class="chart-header">
        <text class="chart-title">信任分布</text>
        <button class="chart-toggle" @click="toggleChartType">
          <text class="toggle-text">{{ chartType === 'pie' ? '饼图' : '柱状图' }}</text>
        </button>
      </view>
      
      <view class="chart-container">
        <canvas 
          id="trustDistributionChart" 
          class="trust-chart"
          :style="{ width: '100%', height: '300rpx' }"
        ></canvas>
      </view>
    </view>

    <!-- 信任趋势图表 -->
    <view class="chart-section">
      <view class="chart-header">
        <text class="chart-title">信任趋势</text>
        <view class="time-range-selector">
          <button 
            class="range-btn" 
            :class="{ active: selectedRange === '7d' }"
            @click="setTimeRange('7d')"
          >
            7天
          </button>
          <button 
            class="range-btn" 
            :class="{ active: selectedRange === '30d' }"
            @click="setTimeRange('30d')"
          >
            30天
          </button>
          <button 
            class="range-btn" 
            :class="{ active: selectedRange === 'all' }"
            @click="setTimeRange('all')"
          >
            全部
          </button>
        </view>
      </view>
      
      <view class="chart-container">
        <canvas 
          id="trustTrendChart" 
          class="trust-chart"
          :style="{ width: '100%', height: '300rpx' }"
        ></canvas>
      </view>
    </view>

    <!-- 信任分析报告 -->
    <view class="analysis-section">
      <text class="section-title">信任分析报告</text>
      
      <view class="analysis-cards">
        <view class="analysis-card">
          <text class="analysis-title">信任健康度</text>
          <view class="health-meter">
            <view class="meter-fill" :style="{ width: trustHealth + '%' }"></view>
          </view>
          <text class="health-text">{{ getHealthText() }}</text>
        </view>
        
        <view class="analysis-card">
          <text class="analysis-title">最活跃卡牌</text>
          <view class="active-card" v-if="mostActiveCard">
            <text class="card-icon">{{ mostActiveCard.icon }}</text>
            <text class="card-name">{{ mostActiveCard.name }}</text>
            <text class="activity-count">{{ mostActiveCard.activityCount }}次操作</text>
          </view>
        </view>
        
        <view class="analysis-card">
          <text class="analysis-title">信任建议</text>
          <view class="suggestions-list">
            <view 
              class="suggestion-item" 
              v-for="suggestion in trustSuggestions" 
              :key="suggestion.id"
            >
              <text class="suggestion-icon">{{ suggestion.icon }}</text>
              <text class="suggestion-text">{{ suggestion.text }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 数据导出 -->
    <view class="export-section">
      <button class="export-btn" @click="exportTrustData">
        <text class="export-icon">📊</text>
        <text class="export-text">导出信任数据</text>
      </button>
      
      <button class="import-btn" @click="importTrustData">
        <text class="import-icon">📥</text>
        <text class="import-text">导入信任数据</text>
      </button>
    </view>

    <!-- 数据导入弹窗 -->
    <view class="import-modal" v-if="showImportModal" @click="closeImportModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">导入信任数据</text>
          <button class="close-btn" @click="closeImportModal">×</button>
        </view>
        
        <view class="modal-body">
          <text class="import-tip">请选择要导入的信任数据文件</text>
          <input 
            type="file" 
            class="file-input" 
            accept=".json"
            @change="handleFileImport"
          />
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import trustCardManager from '@/utils/trust-card-manager.js'

export default {
  name: 'TrustDashboard',
  data() {
    return {
      trustStats: {},
      trustHistory: [],
      chartType: 'pie',
      selectedRange: '7d',
      showImportModal: false,
      distributionChart: null,
      trendChart: null
    }
  },
  
  computed: {
    trustHealth() {
      const { totalCards, highTrustCards, brokenTrustCards } = this.trustStats
      if (totalCards === 0) return 0
      
      const healthScore = ((highTrustCards * 2) - brokenTrustCards) / (totalCards * 2) * 100
      return Math.max(0, Math.min(100, healthScore))
    },
    
    mostActiveCard() {
      // 这里应该从信任历史中计算最活跃的卡牌
      // 暂时返回模拟数据
      return {
        icon: '🤝',
        name: '协作卡',
        activityCount: 15
      }
    },
    
    trustSuggestions() {
      const suggestions = []
      
      if (this.trustStats.brokenTrustCards > 0) {
        suggestions.push({
          id: 'repair',
          icon: '🔧',
          text: `有${this.trustStats.brokenTrustCards}张卡牌信任破裂，建议优先修复`
        })
      }
      
      if (this.trustStats.averageTrust < 50) {
        suggestions.push({
          id: 'improve',
          icon: '📈',
          text: '平均信任值较低，建议增加合作行为'
        })
      }
      
      if (this.trustStats.highTrustCards === 0) {
        suggestions.push({
          id: 'build',
          icon: '🏗️',
          text: '还没有高度信任的卡牌，建议建立长期合作关系'
        })
      }
      
      return suggestions
    }
  },
  
  onLoad() {
    this.loadTrustData()
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  
  onShow() {
    this.loadTrustData()
    this.$nextTick(() => {
      this.updateCharts()
    })
  },
  
  methods: {
    // 加载信任数据
    loadTrustData() {
      trustCardManager.loadData()
      this.trustStats = trustCardManager.getTrustStats()
      this.trustHistory = trustCardManager.getTrustHistory(50)
    },
    
    // 初始化图表
    initCharts() {
      this.initDistributionChart()
      this.initTrendChart()
    },
    
    // 初始化分布图表
    initDistributionChart() {
      const ctx = document.getElementById('trustDistributionChart')
      if (!ctx) return
      
      const data = {
        labels: ['高度信任', '一般信任', '低度信任', '信任破裂'],
        datasets: [{
          data: [
            this.trustStats.highTrustCards,
            this.trustStats.mediumTrustCards,
            this.trustStats.lowTrustCards,
            this.trustStats.brokenTrustCards
          ],
          backgroundColor: [
            '#4caf50',
            '#ff9800',
            '#ff5722',
            '#f44336'
          ]
        }]
      }
      
      const options = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'bottom'
          }
        }
      }
      
      // 这里需要引入Chart.js库
      // this.distributionChart = new Chart(ctx, {
      //   type: this.chartType,
      //   data: data,
      //   options: options
      // })
    },
    
    // 初始化趋势图表
    initTrendChart() {
      const ctx = document.getElementById('trustTrendChart')
      if (!ctx) return
      
      const trendData = this.generateTrendData()
      
      const data = {
        labels: trendData.labels,
        datasets: [{
          label: '平均信任值',
          data: trendData.values,
          borderColor: '#667eea',
          backgroundColor: 'rgba(102, 126, 234, 0.1)',
          fill: true
        }]
      }
      
      const options = {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: true,
            max: 100
          }
        }
      }
      
      // 这里需要引入Chart.js库
      // this.trendChart = new Chart(ctx, {
      //   type: 'line',
      //   data: data,
      //   options: options
      // })
    },
    
    // 生成趋势数据
    generateTrendData() {
      const days = this.selectedRange === '7d' ? 7 : this.selectedRange === '30d' ? 30 : 90
      const labels = []
      const values = []
      
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        labels.push(date.toLocaleDateString())
        
        // 模拟信任值变化
        const baseValue = this.trustStats.averageTrust || 50
        const variation = (Math.random() - 0.5) * 20
        values.push(Math.max(0, Math.min(100, baseValue + variation)))
      }
      
      return { labels, values }
    },
    
    // 切换图表类型
    toggleChartType() {
      this.chartType = this.chartType === 'pie' ? 'bar' : 'pie'
      this.updateCharts()
    },
    
    // 设置时间范围
    setTimeRange(range) {
      this.selectedRange = range
      this.updateCharts()
    },
    
    // 更新图表
    updateCharts() {
      if (this.distributionChart) {
        this.distributionChart.destroy()
        this.initDistributionChart()
      }
      
      if (this.trendChart) {
        this.trendChart.destroy()
        this.initTrendChart()
      }
    },
    
    // 获取健康度文本
    getHealthText() {
      if (this.trustHealth >= 80) return '非常健康'
      if (this.trustHealth >= 60) return '健康'
      if (this.trustHealth >= 40) return '一般'
      if (this.trustHealth >= 20) return '需要关注'
      return '需要修复'
    },
    
    // 导出信任数据
    exportTrustData() {
      const data = trustCardManager.exportTrustData()
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      
      const a = document.createElement('a')
      a.href = url
      a.download = `trust-data-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      uni.showToast({
        title: '数据导出成功',
        icon: 'success'
      })
    },
    
    // 导入信任数据
    importTrustData() {
      this.showImportModal = true
    },
    
    // 关闭导入弹窗
    closeImportModal() {
      this.showImportModal = false
    },
    
    // 处理文件导入
    handleFileImport(event) {
      const file = event.target.files[0]
      if (!file) return
      
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result)
          const success = trustCardManager.importTrustData(data)
          
          if (success) {
            this.loadTrustData()
            this.updateCharts()
            uni.showToast({
              title: '数据导入成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: '数据导入失败',
              icon: 'none'
            })
          }
        } catch (error) {
          uni.showToast({
            title: '文件格式错误',
            icon: 'none'
          })
        }
      }
      reader.readAsText(file)
    }
  }
}
</script>

<style scoped>
.trust-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
}

/* 仪表盘头部 */
.dashboard-header {
  text-align: center;
  margin-bottom: 30rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.dashboard-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.dashboard-subtitle {
  font-size: 24rpx;
  color: #666;
}

/* 信任概览 */
.trust-overview {
  margin-bottom: 30rpx;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
}

.overview-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  padding: 24rpx;
  text-align: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.card-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
  display: block;
  margin-bottom: 8rpx;
}

.card-label {
  font-size: 20rpx;
  color: #666;
}

/* 图表区域 */
.chart-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.chart-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.chart-toggle {
  background: #667eea;
  color: white;
  border: none;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  cursor: pointer;
}

.time-range-selector {
  display: flex;
  gap: 8rpx;
}

.range-btn {
  padding: 6rpx 12rpx;
  background: #f0f0f0;
  border: none;
  border-radius: 6rpx;
  font-size: 18rpx;
  color: #666;
  cursor: pointer;
}

.range-btn.active {
  background: #667eea;
  color: white;
}

.chart-container {
  position: relative;
  height: 300rpx;
}

.trust-chart {
  width: 100%;
  height: 100%;
}

/* 分析区域 */
.analysis-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.analysis-cards {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.analysis-card {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
}

.analysis-title {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

/* 健康度仪表 */
.health-meter {
  width: 100%;
  height: 12rpx;
  background: #e0e0e0;
  border-radius: 6rpx;
  overflow: hidden;
  margin-bottom: 8rpx;
}

.meter-fill {
  height: 100%;
  background: linear-gradient(90deg, #4caf50, #8bc34a);
  border-radius: 6rpx;
  transition: width 0.5s ease;
}

.health-text {
  font-size: 18rpx;
  color: #666;
}

/* 活跃卡牌 */
.active-card {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.card-icon {
  font-size: 24rpx;
}

.card-name {
  flex: 1;
  font-size: 20rpx;
  color: #333;
}

.activity-count {
  font-size: 18rpx;
  color: #667eea;
  font-weight: bold;
}

/* 建议列表 */
.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 12rpx;
  background: white;
  border-radius: 8rpx;
}

.suggestion-icon {
  font-size: 16rpx;
}

.suggestion-text {
  font-size: 16rpx;
  color: #333;
}

/* 导出区域 */
.export-section {
  display: flex;
  gap: 16rpx;
  margin-bottom: 30rpx;
}

.export-btn,
.import-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx 24rpx;
  border: none;
  border-radius: 12rpx;
  font-size: 22rpx;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.export-btn {
  background: linear-gradient(135deg, #4caf50, #8bc34a);
  color: white;
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
}

.import-btn {
  background: linear-gradient(135deg, #2196f3, #03a9f4);
  color: white;
  box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.3);
}

.export-btn:hover,
.import-btn:hover {
  transform: translateY(-2rpx);
}

.export-icon,
.import-icon {
  font-size: 18rpx;
}

.export-text,
.import-text {
  font-size: 20rpx;
}

/* 导入弹窗 */
.import-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 500rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.modal-title {
  font-size: 28rpx;
  font-weight: bold;
}

.close-btn {
  background: none;
  border: none;
  font-size: 32rpx;
  color: white;
  cursor: pointer;
  padding: 8rpx;
}

.modal-body {
  padding: 24rpx;
}

.import-tip {
  font-size: 20rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.file-input {
  width: 100%;
  padding: 12rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 18rpx;
}

/* 响应式设计 */
@media (max-width: 768rpx) {
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .chart-header {
    flex-direction: column;
    gap: 12rpx;
    align-items: flex-start;
  }
  
  .time-range-selector {
    flex-wrap: wrap;
  }
  
  .export-section {
    flex-direction: column;
  }
}
</style>

